﻿using AutoUpdate.Log;
using ScannerApp.Common;
using ScannerApp.Common.PLC;
using ScannerApp.Common.Print;
using ScannerApp.Model;
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.IO.Pipes;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using static ICCEmbedded.SharpZipLib.Zip.ExtendedUnixData;
using static ScannerApp.Common.PopMessageHelper;
using static ScannerApp.Common.Print.TSCLIB;
using static ScannerApp.Model.OperationType;

namespace ScannerApp.Business
{
    /// <summary>
    /// 网络版
    /// DilutionPLC.xaml 的交互逻辑
    /// </summary>
    public partial class PackingPLC : Window
    {
        private bool _disposed = false;

        private void ReleaseResources()
        {
            if (_disposed) return;

            // 停止定时器
            if (timer_heartbeat != null)
            {
                timer_heartbeat.Stop();
                timer_heartbeat.Tick -= heartbeat;
            }

            //if (timerelash != null)
            //{
            //    timerelash.Stop();
            //    timerelash.Tick -= relash;
            //}

            //if (timer != null)
            //{
            //    timer.Stop();
            //    timer.Dispose();
            //}

            //// 关闭串口
            //if (sp != null && sp.IsOpen)
            //{
            //    sp.DataReceived -= sp_DataReceived;
            //    sp.Close();
            //    sp.Dispose();
            //}

            // 断开PLC连接
            DMTDeltaPLC.DisConnPLC();

            _disposed = true;
        }

        protected override void OnClosed(EventArgs e)
        {
            ReleaseResources();
            base.OnClosed(e);
        }

        ScanApp.ScanAppSoapClient sa = new ScanApp.ScanAppSoapClient();
        ComSet wcs = new ComSet();
        string SelectBQ = "DemoBoarID";
        string Com = "", BaudRate = "", DataBits = "", StopRate = "", ParityRate = "";
        IniFiles ini = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\ScanAppConfig.INI");
        IniFiles iniprint = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\PrintIni.INI");
        IniFiles iniBreed = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\BreedDic.INI");
        string BreedDir = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\BreedDic.INI";
        List<string> BreedList = new List<string>();
        string printIP = "";
        private string PLCip = "192.168.1.5";
        System.Windows.Threading.DispatcherTimer timer_heartbeat = new System.Windows.Threading.DispatcherTimer();
        System.Windows.Threading.DispatcherTimer printtimer = new System.Windows.Threading.DispatcherTimer();
        System.Windows.Threading.DispatcherTimer relashTimer = new System.Windows.Threading.DispatcherTimer();
        System.Windows.Threading.DispatcherTimer D76Timer = new System.Windows.Threading.DispatcherTimer();
        bool criticalstop = false;//紧急按钮
        private int dyfs = 0;//打印份数 
        private int dylsh = 0;
        private int templsh = 0;
        private bool b_result = false;//是否打印
        private static Mutex m_Mutex = new Mutex();
        private string strWorkID = "";
        private int errorCode = 0, errorCode81 = 0;//错误代码 
        private int temperCode = 0, tempCode81 = 0;
        private string PrintErrorMsg = ""; string PLCerrorMSG = "";
        private string D76TimerValue = "200";//毫秒
        bool isshow_ = false;//是否弹窗
        bool IsInterNet = false;
        bool IsZebarPrint = false;
        string PrintStyle = "";

        bool IsFirst = true;

        bool F0 = false, F1 = false, F2 = false, F3 = false, F4 = false, F8 = false, F9 = false, F10 = false,
            F80 = false, F81 = false,
            F87 = false, F88 = false;

        string ShortName = "";

        Rect rcnormal;//定义一个全局rect记录还原状态下窗口的位置和大小。
        public PackingPLC()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Maximized;

            czy.Text = publicclass.UserName;
            tm1.Focus();
            printIP = ini.IniReadValue("TCPIP", "PrintIP");
            LoadBreedFile();
            initPLC();
            //心跳，包括重连
            timer_heartbeat.Interval = TimeSpan.FromSeconds(1);
            timer_heartbeat.Tick += heartbeat;
            timer_heartbeat.Start();

            relashTimer.Interval = TimeSpan.FromMilliseconds(200);
            relashTimer.Tick += relashTime;
            //try
            //{
            //    D76TimerValue = ini.IniReadValue("其他参数", "PrintToPLC");
            //}
            //catch {
            //    D76TimerValue = "500";
            //}
            //D76Timer.Interval = TimeSpan.FromMilliseconds(stringtoint( D76TimerValue));
            //D76Timer.Tick += D76Time;
            //D76Timer.Start();

            edit_save(false);
            MouseLeftActive();
            BQ(true);
            IsZebarPrintStyle();
        }
        /// <summary>
        /// 是否是斑马打印机
        /// </summary>
        /// <returns></returns>
        //private void IsZebarPrintStyle()
        //{

        //    string printsytle = ini.IniReadValue("打印类型", "PrintStyle");
        //    if (printsytle != "")
        //    {
        //        if (printsytle == PrintTypes.Zebra.ToString()) IsZebarPrint = true;
        //       else if (printsytle == PrintTypes.ZebraZD420.ToString()) IsZebarPrint = true;
        //    }
        //}

        private Tuple<bool, string> IsZebarPrintStyle()
        {
            string flag = ""; bool IsZer = false;
            string printsytle = ini.IniReadValue("打印类型", "PrintStyle");
            if (printsytle != "")
            {
                if (printsytle == PrintTypes.Zebra.ToString())
                {
                    flag = PrintTypes.Zebra.ToString();
                    PrintStyle = PrintTypes.Zebra.ToString();
                    IsZer = true;
                    IsZebarPrint = true;
                }
                else if (printsytle == PrintTypes.ZebraZD420.ToString())
                {
                    flag = PrintTypes.ZebraZD420.ToString();
                    PrintStyle = PrintTypes.ZebraZD420.ToString();
                    IsZer = true;
                    IsZebarPrint = true;
                }
                else if (printsytle == PrintTypes.Gainscha.ToString())
                {
                    flag = PrintTypes.Gainscha.ToString();
                    PrintStyle = PrintTypes.Gainscha.ToString();
                    IsZer = false;
                    IsZebarPrint = false;
                }
            }
            return new Tuple<bool, string>(IsZer, flag);
        }

        void BQ(bool flag)
        {
            bq1.Background = flag ? System.Windows.Media.Brushes.Blue : System.Windows.Media.Brushes.Navy;
            bq2.Background = !flag ? System.Windows.Media.Brushes.Blue : System.Windows.Media.Brushes.Navy;
            d1.Visibility = flag ? Visibility.Collapsed : Visibility.Visible;
            d2.Visibility = flag ? Visibility.Collapsed : Visibility.Visible;
            //boarID1.Visibility = flag ? Visibility.Collapsed : Visibility.Visible;
        }

        void MouseLeftActive()
        {
            boarID1.AddHandler(System.Windows.Controls.TextBox.MouseLeftButtonDownEvent, new MouseButtonEventHandler(b1_mlb), true);
            boarID2.AddHandler(System.Windows.Controls.TextBox.MouseLeftButtonDownEvent, new MouseButtonEventHandler(b1_mlb), true);
            boarID3.AddHandler(System.Windows.Controls.TextBox.MouseLeftButtonDownEvent, new MouseButtonEventHandler(b1_mlb), true);
            boarID4.AddHandler(System.Windows.Controls.TextBox.MouseLeftButtonDownEvent, new MouseButtonEventHandler(b1_mlb), true);
            boarID5.AddHandler(System.Windows.Controls.TextBox.MouseLeftButtonDownEvent, new MouseButtonEventHandler(b1_mlb), true);
            UseBefore.AddHandler(System.Windows.Controls.DatePicker.MouseLeftButtonDownEvent, new MouseButtonEventHandler(b1_mlb1), true);
            ProdData.AddHandler(System.Windows.Controls.DatePicker.MouseLeftButtonDownEvent, new MouseButtonEventHandler(b1_mlb1), true);
        }

        private void relashTime(object source, EventArgs e)
        {


            UIAction(() =>
            {
                relash();
            });

        }
        private void D76Time(object source, EventArgs e)
        {

            UIAction(() =>
            {
                writeD76();
            });

        }
        void writeD76()
        {
            try
            {
                if (IsZebarPrint)
                    DMTDeltaPLC.SetDReg(76, stringtoint(GetZebarPrintStatus()));//打印机状态无处理给PLC
                else DMTDeltaPLC.SetDReg(76, stringtoint(GetPrintStatus()));//打印机状态无处理给PLC- 
            }
            catch { }

        }
        int clcs = 1;
        private void heartbeat(object source, EventArgs e)
        {

            try
            {
                double result = 0, result81 = 0;
                int r = DMTDeltaPLC.ReadDReg(2000, out result);
                if (r == -1)
                {

                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        relashTimer.Stop();
                        UIAction(() =>
                        {
                            errortips.SetResourceReference(TextBlock.TextProperty, "ErrorPackPLCConnect");
                            errortips.Text = errortips.Text.Replace("[", "[" + clcs);

                        });

                        red.Text = "Reconnect...";
                        timer_heartbeat.Interval = TimeSpan.FromSeconds(10);
                        PLC.Background = System.Windows.Media.Brushes.Red;
                        if (clcs > 1) RconnecPLC();
                        clcs++;
                    }));
                    return;
                }
                else
                {
                    relashTimer.Start();
                    PLC.Background = System.Windows.Media.Brushes.Green;
                    clcs = 1; //HideErrorTips(); 
                    timer_heartbeat.Interval = TimeSpan.FromSeconds(1);
                }


                int r80 = DMTDeltaPLC.ReadDReg(80, out result);
                int r81 = DMTDeltaPLC.ReadDReg(81, out result81);
                if (r80 == -1)
                {
                    ShowErrorTips("80读取错误！", false);
                    return;
                }
                else
                {
                    bool isShowErrorTips = false;
                    if (result != temperCode && result > 0)
                    {
                        isShowErrorTips = true;
                        errorCode = (int)result;
                        temperCode = errorCode;

                        PLCerrorMSG = ""; string PLCerrortips = "";
                        UIAction(() =>
                        {
                            string two = Convert.ToString(errorCode, 2).PadLeft(16, '0');

                            bool a = true; int b = 0; int br = 1; int temp = 0;
                            bool isview = false; isshow_ = false;
                            F0 = false; F1 = false; F2 = false; F3 = false; F4 = false; F8 = false; F9 = false;
                            while (a)
                            {
                                // c = c + two + "\r\n";
                                int x = two.Substring(b).IndexOf("1");
                                if (x == -1) { a = false; break; }

                                b = b + (x + 1);
                                switch (15 - (x + temp))
                                {
                                    case 0: F0 = true; break;
                                    case 1: F1 = true; break;
                                    case 2: F2 = true; break;
                                    case 3: F3 = true; break;
                                    case 4: F4 = true; break;
                                    case 8: criticalstop = true; F8 = true; break;//criticalstop = true;
                                    case 9: criticalstop = true; F9 = true; break;//criticalstop = true;

                                }
                                //  if ( == 0) F0 = true; if (15 - (x + temp) == 1) F1 = true;if (15 - (x + temp) == 2) F2 = true;if (15 - (x + temp) == 3) F3 = true;if (15 - (x + temp) == 4) F4 = true;
                                if ((15 - (x + temp)) == 5 || (15 - (x + temp)) == 6 || (15 - (x + temp)) == 7 || (15 - (x + temp)) >= 11)
                                { isview = true; }
                                //8,9不弹窗显示
                                if ((15 - (x + temp)) == 8 || (15 - (x + temp)) == 9)
                                {
                                    // PLCerrortips = PLCerrortips + GetErrorMsg((15 - (x + temp)).ToString(), "ErrorStatus80");
                                }
                                else
                                {
                                    isshow_ = true;
                                    PLCerrorMSG = PLCerrorMSG + "\r\n" + GetErrorMsg((15 - (x + temp)).ToString(), "ErrorStatus80");
                                    //Enum.GetName(typeof(ErrorStatus), (15 - (x + temp))
                                }

                                temp = temp + x + 1;
                                br++;
                                if (br > 16) break;//防止死循环
                            }
                            PLCerrorMSG = PrintErrorMsg + "\r\n" + PLCerrorMSG;
                            if (isshow_)
                            {
                                IsBreak = true;//自动停止
                                IsPrintCode = false;//打印机命令发送还源
                                ShowModalDialog(true, PLCerrorMSG, isview);
                            }
                            if (F8 || F9)
                            {
                                //仅仅提示错误（不换行） 
                                PLCerrortips = "";
                                if (F8) PLCerrortips = PLCerrortips + GetErrorMsg("8", "ErrorStatus80");
                                //Enum.GetName(typeof(ErrorStatus), 8);
                                if (F9) PLCerrortips = PLCerrortips + GetErrorMsg("9", "ErrorStatus80");
                                ShowErrorTips(PLCerrortips, true, true);
                            }

                            //if (!criticalstop)//非打印机故障，不停止


                        });
                    }

                    if (result81 != tempCode81 && result81 > 0)
                    {
                        isShowErrorTips = true;
                        errorCode81 = (int)result81;
                        tempCode81 = errorCode81;

                        //  PLCerrorMSG = "";  
                        UIAction(() =>
                        {
                            string two = Convert.ToString(errorCode81, 2).PadLeft(16, '0');

                            bool a = true; int b = 0; int br = 1; int temp = 0;
                            bool isview81 = false;
                            F87 = false; F88 = false; F80 = false; F81 = false;
                            while (a)
                            {
                                // c = c + two + "\r\n";
                                int x = two.Substring(b).IndexOf("1");
                                if (x == -1) { a = false; break; }
                                b = b + (x + 1);

                                switch (15 - (x + temp))
                                {
                                    case 0: F80 = true; break; //criticalstop = true;
                                    case 1: F81 = true; break;//criticalstop = true;
                                    case 7: F87 = true; break; //criticalstop = true;
                                    case 8: F88 = true; break;//criticalstop = true;

                                }

                                PLCerrorMSG = PLCerrorMSG + "\r\n" + GetErrorMsg((15 - (x + temp)).ToString(), "ErrorStatus81");
                                //Enum.GetName(typeof(ErrorStatus), (15 - (x + temp))

                                //Enum.GetName(typeof(ErrorStatus), (15 - (x + temp)));

                                temp = temp + x + 1;
                                br++;
                                if (br > 16) break;//防止死循环
                            }
                            PLCerrorMSG = PrintErrorMsg + "\r\n" + PLCerrorMSG;
                            IsBreak = true;//自动停止
                            IsPrintCode = false;//打印机命令发送还源 
                            if (F87 || F88 || F80 || F81) isview81 = true;
                            if (PLCerrorMSG.Length > 4)
                                ShowModalDialog(true, PLCerrorMSG, isview81);

                        });
                    }
                    if (!isShowErrorTips)
                    {
                        isshow_ = false; temperCode = 0;//tempCode81 = 0;  这个不这里处理
                        F8 = false; F9 = false; F10 = false; criticalstop = false;
                        F87 = false; F88 = false; F80 = false; F81 = false;
                        ShowErrorTips("");

                    }


                }
                bool rr = false;
                int m265 = DMTDeltaPLC.ReadMReg(265, out rr);
                if (rr == true)//操作成功
                {
                    bool a = SetM(265, false);
                    if (a)
                    {
                        //lbtips.Content = ("故障清除成功！！");

                    }

                }
                bool rr800 = false;
                int m800 = DMTDeltaPLC.ReadMReg(800, out rr800);
                if (m800 == 1)
                {
                    UIAction(() =>
                    {
                        topzb.IsEnabled = !rr800;
                    });
                }

                int m201 = DMTDeltaPLC.ReadMReg(201, out rr);
                if (rr == true)//操作成功
                {

                    ShowErrorTips("ErrorStatusM2011", true, false);
                    Tips("ErrorStatusM2012");
                }


                int m251 = DMTDeltaPLC.ReadMReg(251, out rr);
                if (rr == true)//操作成功
                {

                    ShowErrorTips("ErrorPackJYEmpty", true, false);

                }
                else
                {
                    //  ShowErrorTips("");
                }

                int m139 = DMTDeltaPLC.ReadMReg(139, out rr);
                if (rr == true)//操作成功
                {
                    UIAction(() =>
                    {
                        start.IsEnabled = false;
                        //bor_print_.IsEnabled = false;
                    });

                }
                else
                {

                    UIAction(() =>
                    {
                        start.IsEnabled = true;
                        //bor_print_.IsEnabled = true;
                    });
                }
                bool rrr = false;
                int m135 = DMTDeltaPLC.ReadMReg(135, out rrr);
                if (rrr == true)//操作成功
                {
                    UIAction(() =>
                    {
                        stop.IsEnabled = false;
                        pause.IsEnabled = false;
                    });
                }
                else
                {
                    UIAction(() =>
                    {
                        stop.IsEnabled = true;
                        pause.IsEnabled = true;
                    });
                }
                int m1000 = DMTDeltaPLC.ReadMReg(800, out rrr);
                if (rrr == true)//操作成功
                {
                    UIAction(() =>
                    {
                        topzb.IsEnabled = false;
                        D218.IsEnabled = false;
                        D408.IsEnabled = false;
                    });
                }
                else
                {
                    UIAction(() =>
                    {
                        topzb.IsEnabled = true;
                        D218.IsEnabled = true;
                        D408.IsEnabled = true;
                    });
                }
                //启动
                bool r113 = false;
                int m113 = DMTDeltaPLC.ReadMReg(113, out r113);
                if (r113 == true)//操作成功
                {
                    templsh = 0;
                    IsBreak = false;
                    DMTDeltaPLC.SetMReg(113, false);
                    btn_start(null, null);

                }

            }
            catch (Exception ex)
            {
                UIAction(() =>
                {
                    red.Text = ex.Message;
                });

            }

        }

        void initPLC()
        {
            loading();
            //打印机参数
            if (ini.ExistINIFile())
            {
                Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                BaudRate = ini.IniReadValue("串口设置", "BaudRate"); //Common.ConfigHelper.GetIni("BaudRate", "");
                DataBits = ini.IniReadValue("串口设置", "DataBits");//Common.ConfigHelper.GetIni("DataBits", "");
                StopRate = ini.IniReadValue("串口设置", "StopRate");//Common.ConfigHelper.GetIni("StopRate", "");
                ParityRate = ini.IniReadValue("串口设置", "ParityRate"); //Common.ConfigHelper.GetIni("ParityRate", "");

                gs.Text = ini.IniReadValue("公司信息", "ComapyName"); //Common.ConfigHelper.GetIni("ParityRate", "");
                dz.Text = ini.IniReadValue("公司信息", "ComapnyAddress"); //Common.ConfigHelper.GetIni("ParityRate", "");
                logo.Text = ini.IniReadValue("公司信息", "logo"); //Common.ConfigHelper.GetIni("ParityRate", "");
                machinename.Text = ini.IniReadValue("公司信息", "machinename");
                machinestyle.Text = ini.IniReadValue("公司信息", "machinestyle");


                int d = 0;
                try
                {
                    d = int.Parse(ini.IniReadValue("公司信息", "CompanyDay"));
                }
                catch { }
                UseBefore.Text = DateTime.Today.AddDays(d).ToString("yyyy-MM-dd");
                UseBefore_.Text = DateTime.Today.AddDays(d).ToString("yyyy-MM-dd");
                ProdData.Text = DateTime.Today.ToString("yyyy-MM-dd");
                ProdData_.Text = DateTime.Today.ToString("yyyy-MM-dd");
            }
            PLCip = ini.IniReadValue("TCPIP", "PLCIP");
            if (!DMTDeltaPLC.ConnPLC(PLCip))
            {
                PLC.Background = System.Windows.Media.Brushes.Red;

            }
            else
            {
                LoadPLCData();
            }
            loadingEnd();
        }
        //实时刷新
        void relash()
        {
            double result = 0;
            string D420_ = DMTDeltaPLC.ReadDReg(420, out result) == 0 ? result.ToString() : "0";
            D420.Text = (stringtofloat(D420_) / 10).ToString("F1");
            string D422_ = DMTDeltaPLC.ReadDReg(422, out result) == 0 ? result.ToString() : "0";
            D422.Text = (stringtofloat(D422_) / 10).ToString("F1");
            D220.Text = DMTDeltaPLC.ReadDReg(220, out result) == 0 ? result.ToString() : "0";
            D218.Text = DMTDeltaPLC.ReadDReg(218, out result) == 0 ? result.ToString() : "0";
            string D500_ = DMTDeltaPLC.ReadDReg(500, out result) == 0 ? result.ToString() : "0";
            D500.Text = (stringtofloat(D500_) / 10).ToString("F1");
            string D501_ = DMTDeltaPLC.ReadDReg(501, out result) == 0 ? result.ToString() : "0";
            D501.Text = (stringtofloat(D501_) / 10).ToString("F1");

            string d20_ = DMTDeltaPLC.ReadDReg(20, out result) == 0 ? result.ToString() : "0";
            D20.Text = (stringtofloat(d20_)).ToString("F1");
            string D408_ = DMTDeltaPLC.ReadDReg(408, out result) == 0 ? result.ToString() : "0";
            D408.Text = (stringtofloat(D408_)).ToString("F1");

            int sfqd = DMTDeltaPLC.ReadMReg(512, out b_result) == 1 ? 1 : 0; //1为启动，0为关闭
            if (sfqd == 1 && b_result) //(bor_print.Text  == "打印机启动")
            {
                bor_print.Text = SelectLan("pdyjqd");// "打印机启用"; 
                topzb.Foreground = System.Windows.Media.Brushes.White;
                bor_print.Foreground = System.Windows.Media.Brushes.Black;

            }
            else if (sfqd == 1 && !b_result) //(bor_print.Text  == "打印机启动")
            {
                bor_print.Text = SelectLan("pdyjqd1");// "打印机关闭";
                bor_print.Foreground = System.Windows.Media.Brushes.Red;

                //bor_print.Foreground = System.Windows.Media.Brushes.Green;
                //bor_print_.Background = System.Windows.Media.Brushes.LightBlue;
            }
            else
            {
                bor_print.Text = "M512 can't read!";
            }
            //补打
            bool r87 = false;
            int M87 = DMTDeltaPLC.ReadMReg(87, out r87);
            if (r87 == true)//操作成功
            {
                DMTDeltaPLC.SetMReg(87, false);
                IsPrintCode = false;
                IsBreak = false;//启用 
                handprint();
            }
        }
        void LoadPLCData()
        {
            //int m100 = M100(true); //主页面，其他页面状态为false
            //if (m100 == 1)//操作成功
            //{
            //}
            int i = DMTDeltaPLC.SetDReg(70, 0);
            // int i1 = DMTDeltaPLC.SetDReg(50, 0);
            double result = 0;
            //butomml.Text = (DMTDeltaPLC.ReadDReg(51, out result) == 0 ? result.ToString() : "0") + "ml";
            relash();
            //打印机启动



            string D70 = DMTDeltaPLC.ReadDReg(70, out result) == 0 ? result.ToString() : "0";

            if (D70 == "0")
            {

                topzb.Content = SelectLan("ptz1");
                topzb.Foreground = System.Windows.Media.Brushes.Purple;
                enable(true);
            }
            else if (D70 == "1")
            {
                enable(false);
                topzb.Content = SelectLan("pzb");
                topzb.Foreground = System.Windows.Media.Brushes.Green;

            }

            printtimer.Interval = TimeSpan.FromMilliseconds(500);
            printtimer.Tick += startAutoprint;

            //printtimer.Start();
            //Thread _ComRec = new Thread(new ThreadStart(Polling)); //查询串口接收数据线程声明
            //_ComRec.Start();//启动线程
            //printtimer = new System.Timers.Timer(1000);//实例化Timer类，设置间隔时间为20毫秒；  
            //printtimer.Elapsed += new System.Timers.ElapsedEventHandler(startAutoprint); //注册中断事件
            //printtimer.Start();//启动定时器


        }
        //下面一排按钮
        void enable(bool flag)
        {
            edit.IsEnabled = flag;
            setting.IsEnabled = flag;
            print.IsEnabled = flag;
            start.IsEnabled = !flag;
            hand.IsEnabled = flag;
            bor_print_.IsEnabled = !flag;
            //==true?Visibility.Collapsed:Visibility.Visible;
        }

        void submit(string tm)
        {
            if (strWorkID == "")
            {
                UIAction(() =>
                {
                    tips.Text = strWorkID + "单据不能为空！";
                });
                return;
            }
            string msg = "";

            try
            {
                msg = sa.Update_boar_collection_status("packing", strWorkID);
            }
            catch (Exception ex)
            {
                msg += ex.Message;
                //sa = new ScanApp.ScanAppSoapClient();
            }
            if (strWorkID != "" && msg == "")
            {
                string para = "{\"EventType\":\"种禽流程打包\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + WorkID.Text + "\",\"Log_Content\":\"" + "【采集打包(状态)】 → A0\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                string msglog = sa.Sys_log(para);
                UIAction(() =>
                {
                    bqyds.Text = "0";
                    tipslan.SetResourceReference(TextBlock.TextProperty, "ErrorPackAutoSubmit");
                    tips.Text = strWorkID + tipslan.Text;
                    ShowErrorTips(strWorkID + tipslan.Text, true, true);
                });

                templsh = 0;
                dyfs = 0;
                IsBreak = true;
                strWorkID = "";
            }
            else
            {
                ShowErrorTips(tm + msg, true, true);
                return;
            }
        }

        //初始化，传入RealyQuantity 时间数量
        void LoadData(string tm)
        {
            IsInterNet = false;
            if (tm.Length <= 1)
            {
                Tips("Errorshortcode");
                return;
            }
            strWorkID = WorkID.Text;//断电恢复
            if (tm == "00000000")// 自动提交
            {
                Write_Docment("submit:" + tm + "自动提交", strWorkID);

                submit(tm);
            }
            else if (tm == "00000001")//手动提交 
            {
                Write_Docment("submit:" + tm + "手动提交", strWorkID);
                submit(tm);
                Clear();
            }
            else
            {
                //  bsm.Text = tm1.Text.Trim();
                tm1.Text = ""; tm1.Focus();
                Clear();
                DataTable lsdt = sa.GetDataTable_collection_condition(tm, "packing");
                if (lsdt == null)
                {
                    Tips("ErrorNoOrder");
                    return;
                }
                else
                {
                    if (lsdt.Rows.Count <= 0)
                    {

                        Tips("ErrorNoOrder");
                        return;
                    }
                    else
                    {
                        foreach (DataRow dr in lsdt.Rows)
                        {
                            IsInterNet = true;

                            ShortName = dr["shortcode"].ToString();//简称
                            WorkID.Text = dr["id"].ToString();
                            strWorkID = dr["id"].ToString();
                            boarBarCode.Text = dr["shortcode"].ToString();//  dr["shortcode"].ToString();
                            boarID.Text = dr["barcode"].ToString();
                            Breed.Text = dr["product_name"].ToString();
                            LotNumber.Text = dr["Serialnumber"].ToString();
                            //UseBefore.Text = dr["Order_date"].ToString();//"yyyy/MM/dd"
                            //UseBefore_.Text = dr["Order_date"].ToString();
                            //ProdData.Text = dr["collectDate"].ToString();
                            //ProdData_.Text = dr["collectDate"].ToString();
                            //新增数据
                            //Density.Text = dr["usemml"].ToString();
                            Density.Text = dr["totmml"].ToString();
                            //Vitality.Text = dr["mnomillions"].ToString();
                            Vitality.Text = dr["motpercen"].ToString();
                            //Vaild.Text = dr["usemillions"].ToString();
                            Vaild.Text = dr["usefulspermperdosis"].ToString();
                            //Total.Text = dr["totmml"].ToString();
                            Total.Text = dr["totalspermsperdosis"].ToString();
                            level.Text = dr["LevelName"].ToString();
                            //  bqyds.Text = dr["PrintCount"].ToString(); ;
                            int scfs = stringtoint(dr["RealyQuantity"].ToString());//produceddosis-printcount
                            dyfs = scfs;
                            dylsh = 1;
                            //生产份数
                            int i = DMTDeltaPLC.SetDReg(218, scfs);
                            if (i == 1)
                            {
                                int D1030 = DMTDeltaPLC.SetMReg(137, true);
                                if (D1030 == 0) { Tips("ErrorPackM137"); }
                            }
                            if (dr["capacity"].ToString() == "0")
                            { Tips("ErrorPackNoZero"); }
                            //每分容量
                            int i2 = DMTDeltaPLC.SetDReg(408, (int)stringtofloat(dr["capacity"].ToString()));
                            if (i2 == 1)
                            {

                            }
                            int d = 0;
                            try
                            {
                                d = int.Parse(ini.IniReadValue("公司信息", "CompanyDay"));
                            }
                            catch { }
                            UseBefore.Text = DateTime.Today.AddDays(d).ToString("yyyy-MM-dd");
                            UseBefore_.Text = DateTime.Today.AddDays(d).ToString("yyyy-MM-dd");
                            ProdData.Text = DateTime.Today.ToString("yyyy-MM-dd");
                            ProdData_.Text = DateTime.Today.ToString("yyyy-MM-dd");

                            UIAction(() =>
                            {

                                //  tips.Text = strWorkID + "正在工作！";
                                tips.SetResourceReference(TextBlock.TextProperty, strWorkID + "nowwork");

                            });
                            //dr["produceddosis"].ToString();
                            //dr["ejaculatedvolume"].ToString();
                            Write_Docment(strWorkID + "开始工作！", strWorkID);
                        }
                        // printBarCode();
                    }
                }
            }

        }

        void Clear()
        {
            boarBarCode.Text = "";
            boarID.Text = "";
            WorkID.Text = "";
            Breed.Text = "";
            LotNumber.Text = "";
            UseBefore.Text = "";
            ProdData.Text = "";
            UseBefore_.Text = "";
            ProdData_.Text = "";

            edit_save(false);
        }


        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }
        /// <summary>
        /// 准备/停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void topzb_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                loading();
                ShowErrorTips("");
                //重新初始化
                cts.Cancel();
                if (topzb.Content.ToString() == SelectLan("pzb"))
                {

                    int i = DMTDeltaPLC.SetDReg(70, 0);
                    if (i == 0)
                    {
                        Tips("ErrorPackPLC");
                        loadingEnd();
                        return;
                        // ShowModalDialog(true, Enum.GetName(typeof(PrintStatus), stringtoint(a)));
                    }
                    topzb.Content = SelectLan("ptz1");
                    topzb.Background = System.Windows.Media.Brushes.Red;
                    enable(true);
                    tm1.IsEnabled = true;
                    tm1.Focus();
                    //新增，如果斑马打印机，先初始化
                    if (IsZebarPrint)
                    {
                        this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate ()

                        {

                            PrintCache.PrintString = "OK";

                            //if(PrintStyle==PrintTypes.ZebraZD420.ToString())
                            //    Common.Print.ZerbarPrint.ZerTSC3(pe);
                            //else 
                            if (PrintStyle == PrintTypes.Zebra.ToString())
                            {
                                //PrintEntity pe = PrintPre();
                                //Common.Print.ZerbarPrint.ZerTSC_LocalImg(pe);
                            }
                            ZebraPrintStatus();

                        });



                    }
                    else JBPrintStatus();

                }
                else if (topzb.Content.ToString() == SelectLan("ptz1"))
                {
                    int i = DMTDeltaPLC.SetDReg(70, 1);

                    if (i == 0)
                    {
                        Tips("ErrorPackPLC");
                        loadingEnd();
                        return;
                        // ShowModalDialog(true, Enum.GetName(typeof(PrintStatus), stringtoint(a)));
                    }

                    // tm2.Focus();
                    topzb.Content = SelectLan("pzb");
                    topzb.Background = System.Windows.Media.Brushes.Green;
                    enable(false);
                    tm1.IsEnabled = false;
                }
                loadingEnd();
            }
            catch (Exception ex)
            {
                loadingEnd();
                Logger.Instance.WriteLog(publicclass.UserName + "[打包]" + ex.Message, LogType.Error, "Packing");
            }
        }

        private void bor_print_MouseLeftDown(object sender, MouseButtonEventArgs e)
        {
            loading();
            if (bor_print.Text == SelectLan("pdyjqd1") || bor_print.Text == SelectLan("p5122"))
            {
                int sfqd = DMTDeltaPLC.SetMReg(512, true) == 1 ? 1 : 0; //1为启动，0为关闭
                if (sfqd == 1)
                {
                    b_result = true;
                    bor_print.Text = SelectLan("pdyjqd");// "打印机启用";
                    topzb.Foreground = System.Windows.Media.Brushes.White;
                    bor_print_.Background = System.Windows.Media.Brushes.LightGreen;
                }
                else
                {
                    bor_print.Text = SelectLan("p5121");// "M512无法操作1";
                }

            }
            else if (bor_print.Text.ToString() == SelectLan("pdyjqd") || bor_print.Text == SelectLan("p5121"))
            {
                int sfqd = DMTDeltaPLC.SetMReg(512, false) == 1 ? 1 : 0; //1为启动，0为关闭
                if (sfqd == 1)
                {
                    b_result = false;
                    bor_print.Text = SelectLan("pdyjqd1");// "打印机关闭";
                    bor_print.Foreground = System.Windows.Media.Brushes.Green;
                    bor_print_.Background = System.Windows.Media.Brushes.LightBlue;
                    if (IsZebarPrint) Common.ZebarPrint.CloseConnet();
                }
                else
                {
                    bor_print.Text = SelectLan("p5122");// "M512无法操作2";
                }
            }
            loadingEnd();
        }
        //标签1
        private void bq1_MouseLeftDown(object sender, MouseButtonEventArgs e)
        {
            SelectBQ = "DemoBoarID";
            BQ(true);

        }
        //标签2
        private void bq2_MouseLeftDown(object sender, MouseButtonEventArgs e)
        {
            SelectBQ = "DemoBoarIDs";
            BQ(false);
        }
        //退出
        private void tc_MouseLeftDown(object sender, MouseButtonEventArgs e)
        {

            tipslan.SetResourceReference(TextBlock.TextProperty, "oClose");
            MessageBoxResult result = System.Windows.MessageBox.Show(tipslan.Text, "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
            else
            {

            }

        }
        //桌面
        private void zm_MouseLeftDown(object sender, MouseButtonEventArgs e)
        {

            WindowState = WindowState.Minimized;

        }
        //关机
        private void gj_MouseLeftDown(object sender, MouseButtonEventArgs e)
        {
            tipslan.SetResourceReference(TextBlock.TextProperty, "oCloseComputer");
            MessageBoxResult result = System.Windows.MessageBox.Show(tipslan.Text, "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                ProcessStartInfo ps = new ProcessStartInfo();
                ps.FileName = "shutdown.exe";
                ps.Arguments = "-s -t 1";
                Process.Start(ps);
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
            else
            {

            }

            //PopMessageHelper.ShowMessage("关机" + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

        }
        //返回
        private void btn_back_Click(object sender, RoutedEventArgs e)
        {
            initPLC();
            btn_visable2.Visibility = Visibility.Collapsed;
            btn_visable1.Visibility = Visibility.Visible;
            SecndHome.Visibility = Visibility.Collapsed;
            Home.Visibility = Visibility.Visible;
        }
        //编辑
        private void btn_edit(object sender, RoutedEventArgs e)
        {
            if (edit_.Text.ToString() == SelectLan("pbj"))
            {
                print.IsEnabled = false;
                edit_save(true);
                edit.Background = System.Windows.Media.Brushes.LightCoral;
                edit_.Text = SelectLan("pbj1");
                BQ(false);
            }
            else
            {
                print.IsEnabled = true;
                edit.Background = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#FF0B479F"));

                edit_save(false);
                edit_.Text = SelectLan("pbj");
                if (SelectBQ == "DemoBoarID")
                    BQ(true);
                else BQ(false);
            }

        }
        //编辑/保存
        void edit_save(bool flag)
        {
            if (!IsFirst)
            {
                ini.IniWriteValue("BoarIDText", "b0", boarBarCode.Text);
                ini.IniWriteValue("BoarIDText", "LotNumber", LotNumber.Text);
                ini.IniWriteValue("BoarIDText", "Breed", Breed.Text);
                ini.IniWriteValue("BoarIDText", "WorkID", WorkID.Text);
                ini.IniWriteValue("BoarIDText", "dysltxt", D218.Text);
                ini.IniWriteValue("BoarIDText", "Density", Density.Text);
                ini.IniWriteValue("BoarIDText", "Vitality", Vitality.Text);
                ini.IniWriteValue("BoarIDText", "Vaild", Vaild.Text);
                ini.IniWriteValue("BoarIDText", "Total", Total.Text);
            }
            LotNumber.Text = ini.IniReadValue("BoarIDText", "LotNumber");
            Breed.Text = ini.IniReadValue("BoarIDText", "Breed");
            WorkID.Text = ini.IniReadValue("BoarIDText", "WorkID");
            D218.Text = ini.IniReadValue("BoarIDText", "dysltxt");
            Density.Text = ini.IniReadValue("BoarIDText", "Density");
            Vitality.Text = ini.IniReadValue("BoarIDText", "Vitality");
            Vaild.Text = ini.IniReadValue("BoarIDText", "Vaild");
            Total.Text = ini.IniReadValue("BoarIDText", "Total");
            if (dyfs == 0)
                dyfs = stringtoint(D218.Text);
            strWorkID = WorkID.Text;//断电恢复

            string b00 = ini.IniReadValue("BoarIDText", "b0");
            boarBarCode.Text = b00;

            WorkID.IsEnabled = flag;
            boarBarCode.IsEnabled = flag;
            boarID1.IsEnabled = flag;
            if (!IsFirst)
                ini.IniWriteValue("BoarIDText", "b1", boarID1.Text);
            string b1 = ini.IniReadValue("BoarIDbgColor", "b1");
            string b11 = ini.IniReadValue("BoarIDText", "b1");
            boarID1.Text = b11;


            boarID1.Visibility = b1 == "LightCoral" ? Visibility.Visible : Visibility.Hidden;
            boarID1.Background = b1 == "LightCoral" ? System.Windows.Media.Brushes.LightCoral : System.Windows.Media.Brushes.LightBlue;
            if (flag) boarID1.Visibility = Visibility.Visible;
            boarID2.IsEnabled = flag;
            if (!IsFirst)
                ini.IniWriteValue("BoarIDText", "b2", boarID2.Text);
            string b2 = ini.IniReadValue("BoarIDbgColor", "b2");
            string b22 = ini.IniReadValue("BoarIDText", "b2");
            boarID2.Text = b22;


            boarID2.Visibility = b2 == "LightCoral" ? Visibility.Visible : Visibility.Hidden;
            boarID2.Background = b2 == "LightCoral" ? System.Windows.Media.Brushes.LightCoral : System.Windows.Media.Brushes.LightBlue;

            if (flag) boarID2.Visibility = Visibility.Visible;
            boarID3.IsEnabled = flag;
            if (!IsFirst)
                ini.IniWriteValue("BoarIDText", "b3", boarID3.Text);
            string b3 = ini.IniReadValue("BoarIDbgColor", "b3");
            string b33 = ini.IniReadValue("BoarIDText", "b3");
            boarID3.Text = b33;


            boarID3.Visibility = b3 == "LightCoral" ? Visibility.Visible : Visibility.Hidden;
            boarID3.Background = b3 == "LightCoral" ? System.Windows.Media.Brushes.LightCoral : System.Windows.Media.Brushes.LightBlue;

            if (flag) boarID3.Visibility = Visibility.Visible;
            boarID4.IsEnabled = flag;
            if (!IsFirst)
                ini.IniWriteValue("BoarIDText", "b4", boarID4.Text);
            string b4 = ini.IniReadValue("BoarIDbgColor", "b4");
            string b44 = ini.IniReadValue("BoarIDText", "b4");
            boarID4.Text = b44;


            boarID4.Visibility = b4 == "LightCoral" ? Visibility.Visible : Visibility.Hidden;
            boarID4.Background = b4 == "LightCoral" ? System.Windows.Media.Brushes.LightCoral : System.Windows.Media.Brushes.LightBlue;

            if (flag) boarID4.Visibility = Visibility.Visible;
            boarID5.IsEnabled = flag;
            if (!IsFirst)
                ini.IniWriteValue("BoarIDText", "b5", boarID5.Text);
            string b5 = ini.IniReadValue("BoarIDbgColor", "b5");
            string b55 = ini.IniReadValue("BoarIDText", "b5");
            boarID5.Text = b55;

            boarID5.Visibility = b5 == "LightCoral" ? Visibility.Visible : Visibility.Hidden;
            boarID5.Background = b5 == "LightCoral" ? System.Windows.Media.Brushes.LightCoral : System.Windows.Media.Brushes.LightBlue;

            if (flag) boarID5.Visibility = Visibility.Visible;
            Breed.IsEnabled = flag;
            LotNumber.IsEnabled = flag;

            string ck11 = ini.IniReadValue("BoarIDbgColor", "ck1");
            UseBefore_.Text = UseBefore.Text;
            UseBefore.Visibility = flag == true ? Visibility.Visible : Visibility.Collapsed;
            UseBefore_.Visibility = !flag == true ? Visibility.Visible : Visibility.Collapsed;
            UseBefore1.Visibility = ck11 == "LightCoral" ? Visibility.Visible : Visibility.Hidden;
            UseBefore.Background = ck11 == "LightCoral" ? System.Windows.Media.Brushes.LightCoral : System.Windows.Media.Brushes.LightBlue;
            UseBefore.Foreground = System.Windows.Media.Brushes.Black;

            if (flag) UseBefore1.Visibility = Visibility.Visible;
            ProdData_.Text = ProdData.Text;
            ProdData.Visibility = flag == true ? Visibility.Visible : Visibility.Collapsed;
            ProdData_.Visibility = !flag == true ? Visibility.Visible : Visibility.Collapsed;
            string ck22 = ini.IniReadValue("BoarIDbgColor", "ck2");

            ProdData1.Visibility = ck22 == "LightCoral" ? Visibility.Visible : Visibility.Hidden;
            ProdData.Background = ck22 == "LightCoral" ? System.Windows.Media.Brushes.LightCoral : System.Windows.Media.Brushes.LightBlue;
            ProdData.Foreground = System.Windows.Media.Brushes.Black;
            if (flag) ProdData1.Visibility = Visibility.Visible;

            IsFirst = false;
        }
        //boarID
        private void b1_mlb(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Controls.TextBox tb = (System.Windows.Controls.TextBox)sender;
            string a = tb.Tag.ToString();
            if (a == "1")
            {
                string b1 = ini.IniReadValue("BoarIDbgColor", "b1");
                boarID1.Background = b1 == "LightCoral" ? System.Windows.Media.Brushes.LightBlue : System.Windows.Media.Brushes.LightCoral;
                string W_color1 = b1 == "LightBlue" ? "LightCoral" : "LightBlue";
                ini.IniWriteValue("BoarIDbgColor", "b1", W_color1);
            }
            if (a == "2")
            {
                string b2 = ini.IniReadValue("BoarIDbgColor", "b2");
                boarID2.Background = b2 == "LightCoral" ? System.Windows.Media.Brushes.LightBlue : System.Windows.Media.Brushes.LightCoral;
                string W_color2 = b2 == "LightBlue" ? "LightCoral" : "LightBlue";
                ini.IniWriteValue("BoarIDbgColor", "b2", W_color2);
            }
            if (a == "3")
            {
                string b3 = ini.IniReadValue("BoarIDbgColor", "b3");
                boarID3.Background = b3 == "LightCoral" ? System.Windows.Media.Brushes.LightBlue : System.Windows.Media.Brushes.LightCoral;
                string W_color3 = b3 == "LightBlue" ? "LightCoral" : "LightBlue";
                ini.IniWriteValue("BoarIDbgColor", "b3", W_color3);
            }
            if (a == "4")
            {
                string b4 = ini.IniReadValue("BoarIDbgColor", "b4");
                boarID4.Background = b4 == "LightCoral" ? System.Windows.Media.Brushes.LightBlue : System.Windows.Media.Brushes.LightCoral;
                string W_color4 = b4 == "LightBlue" ? "LightCoral" : "LightBlue";
                ini.IniWriteValue("BoarIDbgColor", "b4", W_color4);
            }
            if (a == "5")
            {
                string b5 = ini.IniReadValue("BoarIDbgColor", "b5");
                boarID5.Background = b5 == "LightCoral" ? System.Windows.Media.Brushes.LightBlue : System.Windows.Media.Brushes.LightCoral;
                string W_color5 = b5 == "LightBlue" ? "LightCoral" : "LightBlue";
                ini.IniWriteValue("BoarIDbgColor", "b5", W_color5);
            }

        }
        private void b1_mlb1(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Controls.DatePicker tb = (System.Windows.Controls.DatePicker)sender;
            string a = tb.Tag.ToString();

            if (a == "ck1")
            {
                string ck1 = ini.IniReadValue("BoarIDbgColor", "ck1");
                UseBefore.Background = ck1 == "LightCoral" ? System.Windows.Media.Brushes.LightBlue : System.Windows.Media.Brushes.LightCoral;
                string UseBefore1 = ck1 == "LightBlue" ? "LightCoral" : "LightBlue";

                ini.IniWriteValue("BoarIDbgColor", "ck1", UseBefore1);
            }
            if (a == "ck2")
            {
                string ck2 = ini.IniReadValue("BoarIDbgColor", "ck2");
                ProdData.Background = ck2 == "LightCoral" ? System.Windows.Media.Brushes.LightBlue : System.Windows.Media.Brushes.LightCoral;
                string ProdData1 = ck2 == "LightBlue" ? "LightCoral" : "LightBlue";
                ini.IniWriteValue("BoarIDbgColor", "ck2", ProdData1);
            }
        }

        //设置
        private void btn_setting(object sender, RoutedEventArgs e)
        {
            loading();
            btn_visable2.Visibility = Visibility.Visible;
            btn_visable1.Visibility = Visibility.Collapsed;
            SecndHome.Visibility = Visibility.Visible;
            Home.Visibility = Visibility.Collapsed;
            loadingEnd();
        }

        //启动
        private void btn_start(object sender, RoutedEventArgs e)
        {

            ShowErrorTips("");
            //每次打印，重新获取下打印份数
            dyfs = stringtoint(D218.Text);
            if (D408.Text.Trim() == "0")
            {
                Tips("ErrorPackPrintNoZero");
                return;
            }

            int m101 = DMTDeltaPLC.SetMReg(101, true);
            if (m101 == 1)//操作成功
            {
                //  ShowErrorTips("第一步");
                Write_Docment("第一步", strWorkID);
                templsh = 0;
                IsBreak = false;
                IsPrintCode = false;//还原，从新来
                cts.Cancel();
                //重新初始化
                cts = new CancellationTokenSource();
                tasks = new List<Task>();
                heartbeat(null, null);
                Polling();
                Write_Docment("开始自动打印", strWorkID);

                System.Threading.Timer timer = new System.Threading.Timer(
                  (state) =>
                  {
                      start.Dispatcher.BeginInvoke((Action)delegate ()
                      {
                          int a = DMTDeltaPLC.SetMReg(101, false);
                          if (a == 1)
                          {

                          }

                      });


                  }, null, 1000, Timeout.Infinite);
            }


            loadingEnd();
        } //停止
        private void ja_click(object sender, RoutedEventArgs e)
        {
            //test();return;
            if (strWorkID == "")
            {
                // tipslan.SetResourceReference(TextBlock.TextProperty, "ErrorPackNoJA");
                ShowErrorTips("ErrorPackNoJA", true, false);
                return;
            }
            LoadData("00000001");
        }


        //选择订单
        private void btnSelect_Click(object sender, RoutedEventArgs e)
        {

            SelectOrder so = new SelectOrder();
            so.GetIsStatus = "-95-_-96-";
            // 订阅事件
            so.PassValuesEvent += new SelectOrder.PassValuesHandler(ReceiveValues);

            so.Show();
        }
        //返回订单信息
        private void ReceiveValues(object sender, PassValuesEventArgs e)
        {
            string OrderID = e.OrderID;
            string ShortCode = e.ShortCode;
            object a = e.RowData;
            tm1.Text = OrderID;
            loading();
            try
            {
                LoadData(OrderID);
                edit_save(false);
                tm1.Text = "";
                tm1.Focus();
            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage(tm1.Text + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
            }
            loadingEnd();
        }

        bool IsBreak = false;
        void Polling()
        {
            if (IsBreak) return;
            //  while (true)//一直查询新数据
            {
                double result = 0;
                int r = DMTDeltaPLC.ReadDReg(50, out result);
                dylsh = (int)result;
                if (dylsh == dyfs)
                {// 取消所有任务
                    cts.Cancel();
                    return;
                }

                sleep(50); ;//如果不延时，一直查询，将占用CPU过高
                if (m_Mutex.WaitOne())
                {
                    try
                    {
                        // ShowErrorTips("第二步");
                        Write_Docment("第二步", strWorkID);
                        if (b_result)//M512
                        {
                            Print(true);  //提交一次打印  
                        }
                        else
                        {
                            ShowErrorTips("ErrorPack512", true, false);
                            NoPrint();
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowErrorTips(ex.Message, true, true);
                        Logger.Instance.WriteLog(publicclass.UserName + "[打包]" + ex.Message, LogType.Error, "Packing");

                    }
                    finally
                    {
                        m_Mutex.ReleaseMutex();
                    }

                }
            }

        }

        //自动打印，条件，打印开启，无任何异常
        //private void startAutoprint(object source, ElapsedEventArgs e)
        private void startAutoprint(object sender, EventArgs e)
        {
            if (m_Mutex.WaitOne())
            {
                try
                {
                    if (b_result)//M512
                    {
                        Print(true);  //提交一次打印  
                    }
                    else
                    {
                        ShowErrorTips("ErrorPack512", true, false);
                        NoPrint();
                    }
                }
                catch (Exception ex)
                {
                    ShowErrorTips(ex.Message, true, true);
                    Logger.Instance.WriteLog(publicclass.UserName + "[打包]" + ex.Message, LogType.Error, "Packing");

                }
                finally
                {
                    m_Mutex.ReleaseMutex();
                }

            }

        }

        private void btn_stop(object sender, RoutedEventArgs e)
        {
            loading();
            cts.Cancel();
            Write_Docment("暂停打印", strWorkID);
            int m71 = DMTDeltaPLC.SetMReg(73, true);
            if (m71 == 1)//操作成功
            {
                System.Threading.Timer timer = new System.Threading.Timer(
                           (state) =>
                           {
                               IsBreak = true;

                           }, null, 4000, Timeout.Infinite);

            }

            loadingEnd();

        } //暂停
        private void btn_pause(object sender, RoutedEventArgs e)
        {
            loading();
            Write_Docment("复位", strWorkID);
            int m70 = DMTDeltaPLC.SetMReg(70, true);
            if (m70 == 1)//操作成功
            {
                System.Threading.Timer timer = new System.Threading.Timer(
                           (state) =>
                           {
                               IsBreak = true;

                           }, null, 4000, Timeout.Infinite);
            }
            loadingEnd();
        } //复位
        private void btn_reset(object sender, RoutedEventArgs e)
        {
            loading();
            ShowErrorTips("");
            int m96 = DMTDeltaPLC.SetMReg(96, true);
            if (m96 == 1)//操作成功
            {
                IsBreak = true;//打印停止
                //  int D50 = DMTDeltaPLC.SetDReg(50, 0);//D50打印数量清零
                templsh = 0;
                PrintErrorMsg = ""; temperCode = 0; tempCode81 = 0;
                reset.Background = System.Windows.Media.Brushes.Green;
                System.Threading.Timer timer = new System.Threading.Timer(
                       (state) =>
                       {
                           reset.Dispatcher.BeginInvoke((Action)delegate ()
                           {
                               int a = DMTDeltaPLC.SetMReg(96, false);
                               if (a == 1)
                               {
                                   reset.Background = System.Windows.Media.Brushes.Green;
                                   templsh = 0;
                               }

                           });


                       }, null, 500, Timeout.Infinite);

            }
            loadingEnd();
        } //手动
        private void btn_hand(object sender, RoutedEventArgs e)
        {
            int m100 = M100(false);  //暂时为true
            if (m100 == 1)//操作成功
            {
                PackingHand ph = new PackingHand();
                ph.Width = 500;
                ph.Height = 400;
                ph.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                ph.Closing += ph_Colseing;
                ph.ShowDialog();
            }
        }
        private void ph_Colseing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            M100(true);

        }

        int M100(bool flag)
        {
            int m100 = DMTDeltaPLC.SetMReg(100, flag);//暂时为true
            return m100;
        }


        //条码扫描
        private void tm1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                loading();
                try
                {
                    LoadData(tm1.Text.Trim());
                    edit_save(false);
                    tm1.Text = "";
                    tm1.Focus();
                }
                catch (Exception ex)
                {
                    PopMessageHelper.ShowMessage(tm1.Text + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                }
                loadingEnd();
            }
        }
        //打印 
        private void btn_print(object sender, RoutedEventArgs e)
        {
            loading();
            //打印测试页
            //   TSCLIB.TSC1(printIP,"test","test"+dylsh);
            bool b = printBarCode(false);
            if (!b) ShowErrorTips("ErrorPackPrint", true, false);
            loadingEnd();
        }


        private void NoPrint()
        {

            double result = 0;
            int r = DMTDeltaPLC.ReadDReg(50, out result);
            if (result > 0)//打印当前张
            {
                //!ishand &&
                if (dylsh != templsh)
                {
                    dylsh = (int)result;
                    HideErrorTips();
                    string msg = sa.Update_boar_collection_statusPacking(strWorkID, dylsh, "N", "");
                    if (msg == "")
                    {
                        templsh = dylsh;
                        if (dyfs == dylsh)//提交
                        {
                            LoadData("00000000");
                        }
                    }
                    else
                    {

                        ShowErrorTips(msg, true, true);
                        return;
                    }


                }
            }



        }

        bool IsPrintCode = false;//是否打印命令发送完毕

        /// <summary>
        /// 斑马
        /// </summary>
        /// <returns></returns>
        private string GetZebarPrintStatus()
        {
            string a = "00";
            a = Common.ZebarPrint.GetZebarPrintStatusCode();
            //Common.ZebarPrint.GetZebarPrintStatusZPL();
            return a;
        }

        private string GetPrintStatus()
        {
            string a = "00";
            try
            {

                int BR = stringtoint(BaudRate);//获取或设置串行 波特率bit/s  默认值9600
                int DB = stringtoint(DataBits); ;//获取或设置每个字节的标准数据位长度 默认值8
                int stoprate = stringtoint(StopRate);
                int ParityBits = 0;//获取或设置奇偶校验检查协议    默认值None
                ParityBits = ParityRate == "None" ? 0 : 1;//目前就2个

                ComStatusSet.SetSerial(Com, BR, stoprate, ParityBits, DB);
                a = ComStatusSet.GetStaus();
            }
            catch (Exception ex)
            {
                ShowErrorTips(ex.Message, true, true);
                UIAction(() =>
                {
                    if (ex.Message.Contains("COM"))
                    {
                        try
                        {
                            wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            wcs.updateMainwindowLabel += FuncSettingClosed;
                            wcs.ShowDialog();//模式，弹出！
                        }
                        catch { }
                    }
                });
            }

            return a;
        }
        int ft_error = 0;//容错次数
        int printerror_qz = 0;//缺纸计数
                              //falg true 自动 false 手动
        private void Print(bool flag)
        {

            try
            {
                sleep(50); ;//防止死循环卡住了 
                if (IsBreak)
                {
                    cts.Cancel();
                    return;
                }
                string status = "00";

                if (status == "00")
                {
                    printerror_qz = 0;
                    if (flag)//自动打印
                    {
                        // ShowErrorTips("第五步" );
                        Write_Docment("第3步Print" + flag, strWorkID);
                        if (IsPrintCode)//是否正在打印
                        {
                            PrintSuccess();
                            if (dyfs == dylsh)
                            { // 取消所有任务
                                cts.Cancel();
                                IsBreak = true;//自动停止
                                IsPrintCode = false;//打印机命令发送还源
                                return;//打印到最后一张返回
                            }
                        }

                        double result1 = 0;
                        int r408 = DMTDeltaPLC.ReadDReg(408, out result1);
                        if (result1 == 0)
                        {
                            Tips("ErrorPackPrintNoZero");
                            return;
                        }

                        int r70 = DMTDeltaPLC.ReadDReg(70, out result1);
                        if (result1 == 0)//打印机状态
                        {
                            ShowErrorTips("70 no ready！" + templsh, false);
                            return;
                        }

                        bool rr = false;
                        int m82 = DMTDeltaPLC.ReadMReg(82, out rr);
                        if (rr)
                        {
                            DMTDeltaPLC.SetMReg(82, false);
                            double result = 0;
                            int r = DMTDeltaPLC.ReadDReg(50, out result);
                            dylsh = (int)result;
                            bool b = printBarCode(flag);
                            //UIAction(() => {
                            //    if(IsZebarPrint)
                            //    ZebraPrintStatus();
                            //    else JBPrintStatus();
                            //});

                        }
                        else
                        {

                            Polling();
                        }


                    }
                    else
                    {//手动
                        double result = 0;
                        int r = DMTDeltaPLC.ReadDReg(50, out result);
                        dylsh = (int)result;
                        bool b = printBarCode(flag);
                        if (b)//手动不用返回71，也懒得返回服务器
                        {
                            //synactj("手动");//只异步提交。不返回71
                            //  PrintSuccess();
                        }

                    }

                }



            }
            catch (Exception ex)
            {
                ShowErrorTips("print:" + ex.Message, true, true);

            }
        }
        //等待多少毫秒
        void sleep(int time)
        {
            Thread t = new Thread(o => Thread.Sleep(time));
            t.Start(this);
            while (t.IsAlive)
            {
                //防止UI假死
                DispatcherHelper.DoEvents();
            }
        }
        bool printBarCode(bool ishand)
        {
            bool flag = true;
            if (!IsZebarPrint)
            {
                if (printIP == "")
                {
                    ShowErrorTips("ErrorPackNoPrint", true, false);
                    flag = false;
                }
                UIAction(() =>
                {
                    tasks.Add(RunInUiThreadAsync(() =>
                    {
                        if (ishand)//自动才改变
                            IsPrintCode = true;//打印命令开始发送
                        else IsBreak = true; //手动打印后马上停止
                        Write_Docment(IsPrintCode + "打印数据准备" + dyfs, strWorkID);
                        PrintEntity pe = PrintPre();
                        string f = "";
                        f = TSCLIB.TSC(pe);
                        if (f != "")
                        {
                            ShowModalDialog(true, "打印失败！" + f, true);
                            //flag = false;
                            //ishand = true;
                            //printtimer.Stop();
                        }
                        Write_Docment(ishand + "打印完成！" + dyfs, strWorkID);
                        if (ishand)//自动才改变(异步，有可能被覆盖)
                            IsPrintCode = true;//打印命令开始发送

                        if (ishand)//自动打印才循环
                            Print(ishand);
                    }, cts.Token));
                });
            }
            else //斑马打印
            {
                if (ishand)//自动才改变
                    IsPrintCode = true;//打印命令开始发送
                else IsBreak = true; //手动打印后马上停止
                                     // Write_Docment("第二步打印接收SN号" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"), "PrintTrace");
                PrintEntity pe = PrintPre();
                if (PrintStyle == PrintTypes.ZebraZD420.ToString())
                    Common.Print.ZerbarPrint.ZerTSC2(pe);
                else if (PrintStyle == PrintTypes.Zebra.ToString())
                    Common.Print.ZerbarPrint.ZerTSC_Print(pe);

                if (ishand)//自动打印才循环
                {
                    IsPrintCode = true;//打印命令开始发送
                    Print(ishand);
                }

            }
            return flag;


        }
        void JBPrintStatus()
        {
            if (IsBreak) cts.Cancel();
            string status1 = GetPrintStatus();
            int s1 = DMTDeltaPLC.SetDReg(76, stringtoint(status1));//打印机状态无处理给PLC
            if (status1 != "00")
            {
                IsPrintCode = false;
                errorCode = 14;//错误代码触发265
                int address = 74;//打印机故障 
                int s = DMTDeltaPLC.SetDReg(71, 0);//主动把71置为0
                int i = DMTDeltaPLC.SetDReg(address, stringtoint(status1));
                PrintErrorMsg = GetErrorMsg(status1, "PrintStatus");
                ShowModalDialog(true, PrintErrorMsg + status1 + "\r\n" + PLCerrorMSG, true);
            }
        }
        void ZebraPrintStatus()
        {
            try
            {
                if (IsBreak) cts.Cancel();
                string status2 = Common.ZebarPrint.GetZebarPrintStatusCode();
                //GetZebarPrintStatusZPL();
                int s1 = DMTDeltaPLC.SetDReg(76, stringtoint(status2));//打印机状态无处理给PLC
                Write_Docment("获取打印机状态：" + status2, strWorkID);
                if (status2 != "00" && status2 != "07")
                {
                    IsPrintCode = false;
                    errorCode = 14;//错误代码触发265
                    int address = 74;//打印机故障 
                    int s = DMTDeltaPLC.SetDReg(71, 0);//主动把71置为0
                    int i = DMTDeltaPLC.SetDReg(address, stringtoint(status2));
                    PrintErrorMsg = GetErrorMsg(status2, "PrintStatus");
                    if (PrintErrorMsg == "" || PrintErrorMsg == null) PrintErrorMsg = "未知错误,请检查打印机!!Unknown error,PleaseCheck Printer,error code:" + status2;
                    ShowModalDialog(true, PrintErrorMsg + status2 + "\r\n" + PLCerrorMSG, true);
                }
            }
            catch (Exception e)
            {
                PrintErrorMsg = "未知错误,请检查打印机!" + e.Message;
                ShowModalDialog(true, PrintErrorMsg, true);
            }
        }

        PrintEntity PrintPre()
        {

            string gsmc = gs.Text.Trim();
            string dzmc = dz.Text.Trim();
            string IDS = "";
            if (boarID.Text.Trim() != "") IDS = Left6char(boarID.Text.Trim());

            string b1 = ini.IniReadValue("BoarIDbgColor", "b1");
            if (b1 == "LightCoral") IDS = IDS + ";" + Left6char(boarID1.Text.Trim());
            string b2 = ini.IniReadValue("BoarIDbgColor", "b2");
            if (b2 == "LightCoral") IDS = IDS + ";" + Left6char(boarID2.Text.Trim());
            string b3 = ini.IniReadValue("BoarIDbgColor", "b3");
            if (b3 == "LightCoral") IDS = IDS + ";" + Left6char(boarID3.Text.Trim());
            string b4 = ini.IniReadValue("BoarIDbgColor", "b4");
            if (b4 == "LightCoral") IDS = IDS + ";" + Left6char(boarID4.Text.Trim());
            string b5 = ini.IniReadValue("BoarIDbgColor", "b5");
            if (b5 == "LightCoral") IDS = IDS + ";" + Left6char(boarID5.Text.Trim());
            string UseBefor = "UserDate:2019-11-11";
            string ProDate = "ProDate:2019-11-11";//使用日期+":" 
            if (UseBefore.Text.Trim() != "") UseBefor = syrq_.Text + DateTime.Parse(UseBefore.Text.Trim()).ToString("yyyy-MM-dd");
            string ck1 = ini.IniReadValue("BoarIDbgColor", "ck1");
            // UseBefore1.Background = ck1 == "LightCoral" ? System.Windows.Media.Brushes.LightBlue : System.Windows.Media.Brushes.LightCoral;

            if (ck1 == "LightBlue") UseBefor = "";
            if (ProdData.Text.Trim() != "") ProDate = scrq_.Text + DateTime.Parse(ProdData.Text.Trim()).ToString("yyyy-MM-dd");
            string ck2 = ini.IniReadValue("BoarIDbgColor", "ck2");
            if (ck2 == "LightBlue") ProDate = "";
            string printstr = "";
            int d408 = 0;
            try { d408 = (int)float.Parse(D408.Text.Trim()); } catch { }
            string d408_ml = prl_.Text + d408 + "ml";
            string slevel = vaildtotal2_.Text + level.Text.Trim();
            bool IsSingle = false;
            try
            {
                string ids = iniprint.IniReadValue(SelectBQ, "IDs");
                if (ids.Length > 10)//存在IDs配置，则是多标签
                    IsSingle = false;
            }
            catch { }
            //品种，耳号s（6位），批号，生产日期，容量，序号
            if (IsSingle) printstr = Breed.Text.Trim() + "-" + boarID.Text.Trim() + "-" + LotNumber.Text.Trim() + "-" + ProdData.Text.Trim() + "-" + d408_ml + "-" + dylsh;
            else printstr = Breed.Text.Trim() + "-" + IDS.Replace(";", "/") + "-" + LotNumber.Text.Trim() + "-" + ProdData.Text.Trim() + "-" + d408_ml + "-" + dylsh;
            // printstr = IDS.Replace(";","") + Breed.Text.Trim() + "-" + LotNumber.Text.Trim() + "-" + ProDate;

            //2021-6-30，增加 密度/活力/有效/总精子数
            string sDensity = "", sVitality = "", sVaild = "", sTotal = "";
            try { sDensity = density_.Text.Trim() + Density.Text.Trim() + "M/ml"; } catch { }
            try { sVitality = vitality_.Text.Trim() + Vitality.Text.Trim(); } catch { }
            try { sVaild = AA.Text + printUnit.Text + Vaild.Text.Trim(); } catch { }
            try { sTotal = vaildtotal_.Text + printUnit.Text + Total.Text.Trim(); } catch { }
            printstr = printstr + "-" + sDensity + "-" + sVitality + "-" + sVaild + "-" + sTotal;
            PrintEntity pe = new PrintEntity();
            pe.Bq = SelectBQ;
            pe.P_port = printIP;
            pe.Title = gsmc;
            pe.BarCode = printstr;
            pe.Address = dzmc;
            pe.Breed = pz_.Text + Breed.Text.Trim();
            pe.LotNumber = ph_.Text + LotNumber.Text.Trim();
            pe.UseBefore = UseBefor;
            pe.ProdDate = ProDate;
            pe.FullID = boarID.Text.Trim();
            pe.ID = eb_.Text + ";" + (boarID.Text.Trim());
            pe.Ml = d408_ml;
            pe.IDs = eb_.Text.Replace(":", "") + ";" + IDS;
            pe.Dylsh = "SN:" + dylsh;
            pe.Shortname = density2_.Text + ShortName;//耳号
            pe.Issingle = false;
            pe.SDensity = sDensity;
            pe.SVitality = sVitality;
            pe.SVaild = sVaild;
            pe.STotal = sTotal;
            pe.SLevel = slevel;
            pe.Zdy1 = ini.IniReadValue("公司信息", "bz1");
            pe.Zdy2 = ini.IniReadValue("公司信息", "bz2");
            return pe;
        }


        void PrintSuccess()
        {
            //打印完成信号
            int s = DMTDeltaPLC.SetDReg(71, 1);
            if (s == 1)
            {
                Write_Docment("9流水号" + dylsh + "打印完成;" + dyfs, strWorkID);
                //  ShowErrorTips("第九步");
                IsPrintCode = false;
                //异步提交 
                if (dyfs == dylsh)//符合先停止再说
                {
                    cts.Cancel();
                    Write_Docment("PrintSuccess:" + dylsh + "打印完成，停止" + dyfs, strWorkID);
                    IsBreak = true;//打印完成，停止
                    templsh = 0;
                }
                synactj("自动");
            }
            else
            {
                Write_Docment("流水号" + dylsh + "打印完成信号传输失败=》" + s, strWorkID);
            }
        }
        //异步提交

        private void synactj(string lx)
        {
            UIAction(() =>
            {
                try
                {
                    string msg = sa.Update_boar_collection_statusPacking(strWorkID, dylsh, "Y", lx);
                    if (msg == "")
                    {
                        Write_Docment(lx + ":流水" + dylsh + "上传服务器成功！", strWorkID);
                        Write_Docment("第十步" + IsBreak + "--" + dyfs + "--" + dylsh, strWorkID);
                        ShowErrorTips("第十步" + IsBreak + "--" + dyfs + "--" + dylsh, false);
                        //  Polling();
                        if (dyfs == dylsh)//提交
                        {
                            Write_Docment("异步提交:" + dylsh + "打印完成，停止" + dyfs, strWorkID);
                            IsBreak = true;//打印完成，停止
                            templsh = 0;
                            LoadData("00000000");
                            Write_Docment(lx + ":完成提交成功！", strWorkID);

                        }
                    }
                    else
                    {
                        Write_Docment(lx + ":流水" + dylsh + "上传服务器失败！" + msg, strWorkID);
                        //ShowErrorTips(msg);
                        //return;
                    }
                }
                catch (Exception ex)
                {
                    Write_Docment(lx + ":流水" + dylsh + "上传服务器失败！" + ex.Message, strWorkID);

                }
            });

        }

        //返回时候触发这个函数
        private void FuncSettingClosed(string labelContent)
        {
            initPLC();                                                //    string Com = Common.ConfigHelper.GetIni("Com", "");
            if (Com == "" && labelContent == "0")
            {
                PopMessageHelper.ShowMessage("检测没有初始化串口，无法采集信息，请重新设置！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                wcs.updateMainwindowLabel += FuncSettingClosed;
                wcs.ShowDialog();//模式，弹出！ 

            }
            else { HideErrorTips(); }

        }

        string Left6char(string s)
        {
            if (s.Length >= 6)
                s = s.Substring(s.Length - 6, 6);
            return s;
        }
        //焦点离开
        private void Breed_LostFocus(object sender, RoutedEventArgs e)
        {
            bool IsExist = false;
            for (int i = 0; i < BreedList.Count; i++)
            {
                if (BreedList[i] == Breed.Text)
                    IsExist = true;
            }
            if (!IsExist)
            {
                LoadAdd(Breed.Text);
                BreedList.Add(Breed.Text);
            }
            SaveFile();

        }
        private void LoadAdd(string Data)
        {
            Breed.AddItem(new AutoCompleteEntry(Data, null));
        }
        private void SaveFile()
        {
            List<string> fileList = new List<string>();
            for (int i = 0; i < BreedList.Count; i++)
            {
                fileList.Add(string.Format("{0}☆", BreedList[i]));
            }

            File.WriteAllLines(BreedDir, fileList.ToArray());
        }

        private void LoadBreedFile()
        {
            try
            {
                if (iniBreed.ExistINIFile())
                {
                    string[] rfile = File.ReadAllLines(BreedDir);
                    string[] sp = null;
                    for (int i = 0; i < rfile.Length; i++)
                    {
                        sp = rfile[i].Split('☆');
                        BreedList.Add(sp[0]);
                        LoadAdd(sp[0]);
                    }
                }

            }
            catch
            {
                return;
            }
        }

        private void PLC_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            RconnecPLC();
        }
        void RconnecPLC()
        {
            DMTDeltaPLC.DisConnPLC();
            PLC.Background = System.Windows.Media.Brushes.Red;

            if (DMTDeltaPLC.ConnPLC(PLCip))
            {
                PLC.Background = System.Windows.Media.Brushes.Green;
                LoadPLCData();
                red.Text = "";
            }
            loadingEnd();
        }


        private void ShowModalDialog(bool bShow, string tips, bool isview)
        {

            if (isview)
            {
                qcgz.Visibility = Visibility.Visible;
                sdbd.Visibility = Visibility.Visible;
                sdtb.Visibility = Visibility.Visible;
                M89.Visibility = Visibility.Hidden;
            }
            else
            {
                qcgz.Visibility = Visibility.Visible;
                sdbd.Visibility = Visibility.Hidden;
                sdtb.Visibility = Visibility.Hidden;
                M89.Visibility = Visibility.Visible;
            }
            if (isCosePopWindow())
            {
                this.ModalDialog.IsOpen = bShow;
                if (bShow) { lbtips.Content = tips; }
            }
            // }


            // this.MainPanel.IsEnabled = !bShow;
        }

        //清除故障
        private void qcgz_Click(object sender, RoutedEventArgs e)
        {

            PrintErrorMsg = ""; temperCode = 0; tempCode81 = 0; PLCerrorMSG = "";
            bool f = false; bool is89 = true;
            try
            {
                if (F0)
                { f = SetM(267, true); F0 = false; }
                if (F1)
                { f = SetM(268, true); F1 = false; }
                if (F2)
                { f = SetM(269, true); F2 = false; }
                if (F3)
                { f = SetM(270, true); F3 = false; }
                if (F4)
                { f = SetM(271, true); F4 = false; }
                if (errorCode == 8 || errorCode == 9 || errorCode == 10)
                {

                }
                else
                {
                    is89 = false;
                    f = SetM(265, true);
                    System.Threading.Timer timer = new System.Threading.Timer(
                           (state) =>
                           {
                               qcgz.Dispatcher.BeginInvoke((Action)delegate ()
                               {
                                   bool a = SetM(265, false);
                                   if (a)
                                   {
                                       lbtips.SetResourceReference(ContentProperty, "ErrorPackGZSuccess");

                                   }

                               });


                           }, null, 1000, Timeout.Infinite);
                }
                if (!f)
                {
                    ShowErrorTips("ErrorPackGZFaile", true, false); loadingEnd();
                }
                loadingEnd();
                lbtips.SetResourceReference(ContentProperty, "ErrorPackGZSuccess");
                //双重保证，恢复源来样式
                // resumButton(qcgz, "清除故障");
            }
            catch { }


        }
        //继续
        private void M89_Click(object sender, RoutedEventArgs e)
        {
            bool b = SetM(89, true);

            System.Threading.Timer timer = new System.Threading.Timer(
                         (state) =>
                         {
                             qcgz.Dispatcher.BeginInvoke((Action)delegate ()
                             {
                                 bool a = SetM(89, false);
                                 if (a)
                                 {
                                     lbtips.Content = ("M89继续成功！！");

                                 }

                             });


                         }, null, 1000, Timeout.Infinite);
        }
        //手动补打
        private void sdbd_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                //ishand = true; //ishanding = true;//点一次打一次 
                //IsPrinting = false;//报错复源
                IsPrintCode = false;//打印机命令发送还源
                IsBreak = false;//启用              //printtimer.Stop();
                Write_Docment("开始手动补标", strWorkID);
                handprint();
            }
            catch { }

            //resumButton(sdbd, "手动补打");
        }
        void handprint()
        {
            int sfqd = DMTDeltaPLC.SetMReg(88, true);
            if (sfqd == 1)
            {
                Print(false);
            }
            else
            {
                ShowErrorTips("ErrorPackSDFaile", true, false);
            }
        }
        //手动贴标
        private void sdtb_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                bool f = SetM(86, true);
                if (f)
                {
                    sdtb.Background = System.Windows.Media.Brushes.Green;
                }
                else
                {
                    ShowErrorTips("ErrorPackSDTBFaile", true, false);
                }
                //resumButton(sdtb, "手动贴标");
            }
            catch { }



        }

        void resumButton(System.Windows.Controls.Button bt, string str)
        {
            System.Threading.Timer timer2 = new System.Threading.Timer(
         (state) =>
         {
             bt.Dispatcher.BeginInvoke((Action)delegate ()
             {
                 bt.Content = str;
                 bt.IsEnabled = true;
             });

         }, null, 1000, Timeout.Infinite);
        }


        private void Dlg_Close1_Click(object sender, MouseButtonEventArgs e)
        {

            PrintErrorMsg = ""; temperCode = 0; tempCode81 = 0; PLCerrorMSG = "";
            criticalstop = false;//紧急报警
            IsBreak = false;
            IsPrintCode = false;
            ShowModalDialog(false, "", false);

        }

        private int DAdr = 0;
        //r容量
        private void rl_mld(object sender, MouseButtonEventArgs e)
        {
            aaa.IsOpen = true; DAdr = 408;
            // txtvalue.Text = "0"; ShowModalDialog_value(true, 408, "容量", "灌装容量");

        }
        //热合
        private void rh_mld(object sender, MouseButtonEventArgs e)
        {
            aaa.IsOpen = true; DAdr = 422;
            // txtvalue.Text = "0"; ShowModalDialog_value(true, 422, "热合", "热合");
        }
        //数量
        private void sl_mld(object sender, MouseButtonEventArgs e)
        {
            aaa.IsOpen = true; DAdr = 218;
            //txtvalue.Text = "0"; ShowModalDialog_value(true, 218, "数量", "数量"); 
        }
        //数字提交
        private void btn_tj(object sender, RoutedEventArgs e)
        {

            try
            {
                if (DAdr == 0) return;
                float value = stringtofloat(publicclass.PopNum);
                if (DAdr == 422)
                {

                    if (value > 200)
                    {
                        PopMessageHelper.ShowMessage("设定失败!温度设置不能超过200", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);
                        return;
                    }
                    value = (value * 10);
                }
                int sfqd = DMTDeltaPLC.SetDReg(DAdr, (int)value) == 1 ? 1 : 0; //1为启动，0为关闭
                if (sfqd == 1)
                {
                    relash();
                    aaa.IsOpen = false;
                    // ShowModalDialog_value(false, 0, "", "");
                }
                else
                {
                    Tips(DAdr + "设定失败！");
                }
                if (DAdr == 408)//D408每次手动设置完成后把D1030清零
                {
                    int D1030 = DMTDeltaPLC.SetDReg(1030, 0) == 1 ? 1 : 0;
                    if (D1030 == 0) { Tips("D1030设定失败！"); }
                }
                if (DAdr == 218)//d218是设定灌装数量，在设定完成后需要把m137置1。
                {
                    dyfs = (int)value;
                    int i = DMTDeltaPLC.SetDReg(218, (int)value);
                    int D1030 = DMTDeltaPLC.SetMReg(137, true);
                    if (D1030 == 0) { Tips("D1030设定失败！"); }
                }
            }
            catch (Exception ex)
            { Tips(ex.Message); }
            tm1.Focus();
        }
        private void btn_numclose(object sender, RoutedEventArgs e)
        {
            publicclass.PopNum = "0";
            aaa.IsOpen = false;
        }



        private void Dgb_Click(object sender, RoutedEventArgs e)
        {
            PrintErrorMsg = ""; temperCode = 0; tempCode81 = 0; PLCerrorMSG = "";
            criticalstop = false;//紧急报警
            IsBreak = false;
            IsPrintCode = false;
            ShowModalDialog(false, "", false);
        }

        private void ShowModalDialog_value(bool bShow, int ad, string tips, string title)
        {
            if (isCosePopWindow())
                this.ModalDialog1.IsOpen = bShow;
            if (bShow)
            {
                DAdr = ad;
                txtsd.Text = tips;
                lbsd.Content = title;
            }
            // this.MainPanel.IsEnabled = !bShow;
        }
        private void Dlg_OK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (DAdr == 0) return;
                float value = stringtofloat(txtvalue.Text);
                if (DAdr == 422) value = (value * 10);
                int sfqd = DMTDeltaPLC.SetDReg(DAdr, (int)value) == 1 ? 1 : 0; //1为启动，0为关闭
                if (sfqd == 1)
                {
                    LoadPLCData();
                    ShowModalDialog_value(false, 0, "", "");
                }
                else
                {
                    Tips(DAdr + "设定失败！");
                }
                if (DAdr == 408)//D408每次手动设置完成后把D1030清零
                {
                    int D1030 = DMTDeltaPLC.SetDReg(1030, 0) == 1 ? 1 : 0;
                    if (sfqd == 0) { Tips("D1030设定失败！"); }
                }
            }
            catch (Exception ex)
            { Tips(ex.Message); }
        }
        private void Dlg_Close_Click(object sender, RoutedEventArgs e)
        {
            ShowModalDialog_value(false, 0, "", "");
        }

        private bool SetM(int address, bool flag)
        {
            int sfqd = DMTDeltaPLC.SetMReg(address, flag) == 1 ? 1 : 0; //1为启动，0为关闭
            if (sfqd == 1)
            { return true; }
            else return false;
        }



        private void loading()
        {
            this._loading.Visibility = Visibility.Visible;
        }
        private void loadingEnd()
        {
            this._loading.Visibility = Visibility.Hidden;
        }
        void Tips(string msg)
        {
            UIAction(() =>
            {
                tips.SetResourceReference(TextBlock.TextProperty, msg);
                // tips.Text = msg;
                tm1.Focus();
                Logger.Instance.WriteLog(publicclass.UserName + "[打包]" + msg, LogType.Error, "Packing");

            });
            // PopMessageHelper.ShowMessage("错误:" + msg + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

        }
        /// <summary>
        /// 记录上位机打印记录
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="docment"></param>
        void Write_Docment(string msg, string docment)
        {
            UIAction(() =>
            {
                Logger.Instance.WriteLog_(msg, LogType.Information, docment);

            });
        }
        //显示错误提示
        void ShowErrorTips(string msg, bool isview = true, bool issystem = false)
        {
            UIAction(() =>
            {
                //  errsp.Visibility = Visibility.Visible;
                if (isview)
                {
                    if (issystem) errortips.Text = msg;
                    else
                        errortips.SetResourceReference(TextBlock.TextProperty, msg);
                }
                // errortips.Text = msg;
                if (msg.Length < 1) return;
                Logger.Instance.WriteLog(publicclass.UserName + "[打包]" + msg, LogType.Error, "Packing");

            });

        }//隐藏错误提示
        void HideErrorTips()
        {
            UIAction(() =>
            {
                errsp.Visibility = Visibility.Hidden;
                errortips.Text = "";
            });

        }

        CancellationTokenSource cts = new CancellationTokenSource();
        List<Task> tasks = new List<Task>();

        public async Task RunInUiThreadAsync(Action action, CancellationToken ct)
        {
            while (!ct.IsCancellationRequested)
            {
                await this.Dispatcher.InvokeAsync(() =>
                {
                    if (!ct.IsCancellationRequested) action();
                }, DispatcherPriority.Normal, ct);

                await Task.Delay(100, ct);
            }
        }

        void UIAction(Action action)
        {
            new Thread(() => {
                this.Dispatcher.Invoke(action);
            }).Start();
        }

        void UIActions(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }

        bool isCosePopWindow()
        {
            string close = "false", c = "false";
            try { close = ini.IniReadValue("公司信息", "CloePopWindow"); }
            catch { }
            return close == "true" ? true : false;
        }

        /// <summary>
        /// 多语言获取错误信息
        /// </summary>
        /// <param name="ErrorCode"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        string GetErrorMsg(string ErrorCode, string Type)
        {
            string s = "";
            string RR = Type + ErrorCode;
            tipslan.SetResourceReference(TextBlock.TextProperty, RR);
            s = tipslan.Text;
            return s;
        }

        string SelectLan(string type)
        {
            //UIAction(() =>
            //{
            tipslan.SetResourceReference(TextBlock.TextProperty, type);
            // });

            string r = tipslan.Text;

            return r;
        }
        //public enum PrintStatus
        //{
        //    就绪 = 00,
        //    卡纸 = 02,
        //    开盖 = 41,
        //    开盖且缺纸 = 45,
        //    开机中 = 11,
        //    正在打印 = 20,
        //    缺纸 = 04,
        //    没有返回状态=99

        //}
        //enum ErrorStatus
        //{
        //    _000穿袋动点故障_请检查X1_Y20 = 0,
        //    _001前压动点故障_请检查X21_Y27 = 1,
        //    _002移袋动点故障_请检查X2_X3_Y21 = 2,
        //    _003灌装动点故障_请移除当前精液袋_请检查X5_Y22 = 3,
        //    _004切袋动点故障_请检查X7_Y23 = 4,
        //    _005标签未吸到_请检查X27_Y31 = 5,
        //    _006旋转气缸动点故障_请检查X23_Y24 = 6,
        //    _007贴标气缸动点故障_请检查X25_Y25 = 7,
        //    急停_急停开关被按下_请确认后复位 = 8,
        //    气压不足_请检查气源是否打开 = 9,
        //    //_008急停_急停开关被按下_请确认后复位 = 8,
        //    //_009气压不足_请检查气源是否打开 = 9,
        //    _010精液袋已用完_请更换精液袋 = 10,
        //    _011打印机异常_请检查打印机 = 11,
        //    _012打印机缺纸_请更换标签纸 = 12,
        //    _013标签检测错误 = 13,
        //    _014无碳带 = 14,
        //    _015开盖有纸 = 15
        //}
        //enum ErrorStatus81
        //{  
        //    _016开盖缺纸 = 0,
        //    _017打印机过热 = 1,
        //    _018穿袋原点故障_请检查X0_Y20=2,
        //    _019前压原点故障_请检查X20_Y27_= 3,
        //    _020移袋原点故障_请检查X2_Y21_ = 4,
        //    _021灌装原点故障_请检查X4_Y22_= 5,
        //    _022切袋原点故障_请检查X6_Y23_ = 6,
        //    _023旋转气缸原点故障_请检查X22_Y24_ = 7,
        //    _024贴标气缸原点故障_请检查X24_Y25_ = 8

        // }
        int stringtoint(string a)
        {
            int i = 0;
            try { i = int.Parse(a); } catch { }
            return i;
        }
        int strtoint99(string a)
        {
            int i = 99;
            try { i = int.Parse(a); } catch { }
            return i;
        }
        float stringtofloat(string a)
        {
            float i = 0;
            try { i = float.Parse(a); } catch { }
            return i;
        }
        public static class DispatcherHelper
        {
            [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
            public static void DoEvents()
            {
                DispatcherFrame frame = new DispatcherFrame();
                Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame);
                try { Dispatcher.PushFrame(frame); }
                catch (InvalidOperationException) { }
            }
            private static object ExitFrames(object frame)
            {
                ((DispatcherFrame)frame).Continue = false;
                return null;
            }
        }

    }
}
